package com.hz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hz.dao.RechargeDao;
import com.hz.pojo.Recharge;
import com.hz.pojo.User;
import com.hz.service.RechargeService;
import com.hz.utils.DateUtils;
import com.hz.utils.MassageJsons;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RechargeServiceImpl implements RechargeService {
    @Resource
    private RechargeDao rechargeDao;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public List<Recharge> getRechargeList(String recharge_user_id) throws Exception {
        return rechargeDao.getRechargeList(recharge_user_id);
    }

    @Override
    @Transactional
    public MassageJsons udpUserBalance(String open_id, Double money) {
        try {

            //添加充值信息
            rechargeDao.addRecharge(open_id,money,DateUtils.getCurrentTime());
            //更新软件收益
            stringRedisTemplate.opsForValue().increment("HN520",money);
            //从Redis获取当前充值的对象字符串
            String userjson = stringRedisTemplate.opsForValue().get(open_id);
            //转换为对象
            User user = JSON.parseObject(userjson,User.class);
            //更改对象的余额
            user.getSafetyInfo().setAccount_money(user.getSafetyInfo().getAccount_money()+money);
            //执行充值方法
            rechargeDao.udpUserBalance(open_id,user.getSafetyInfo().getAccount_money());
            //再把对象存入Redis
            stringRedisTemplate.opsForValue().set(open_id,JSONObject.toJSONString(user));
            return new MassageJsons("0","充值成功",user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new MassageJsons("1","充值失败",null);
    }
}
